<template>
  <div class="distribution-page">
    <!-- 标题 -->
    <p class="title">
      <i class="el-icon-truck"></i> 物资分配情况
    </p>
    <el-divider></el-divider>

    <!-- 搜索表单 和 添加按钮 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <div class="left-search">
        <el-form-item label="搜索：">
          <el-input size="small" v-model="searchForm.doneeId" placeholder="输入受捐赠者 ID"></el-input>
        </el-form-item>
        <el-form-item label>
          <el-input size="small" v-model="searchForm.suppliesName" placeholder="输入物资名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addRow">添加</el-button>
          <el-button size="small" icon="el-icon-close" v-show="isSearch" @click="exitSearch">退出搜索</el-button>
        </el-form-item>
      </div>
      <div class="right-search">
        <el-form-item>
          <el-button size="small" type="info" icon="el-icon-takeaway-box" @click="searchStock">查看库存</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 物资接收表格 -->
    <el-table :data="distributionData" border highlight-current-row>
      <el-table-column prop="distributionId" label="物资 ID"></el-table-column>
      <el-table-column prop="doneeId" label="受捐赠人 ID"></el-table-column>
      <el-table-column prop="suppliesName" label="物资名称"></el-table-column>
      <el-table-column prop="type" label="种类"></el-table-column>
      <el-table-column prop="specifications" label="规格"></el-table-column>
      <el-table-column prop="units" label="单位"></el-table-column>
      <el-table-column prop="number" label="数量"></el-table-column>
      <el-table-column prop="distributeTime" label="分配时间"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row.distributionId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页栏 -->
    <el-pagination
      background
      :total="totalRow"
      :current-page="currentPage"
      :page-sizes="[15, 30, 50, 100]"
      :page-size="pageSize"
      @current-change="currentChange"
      @size-change="sizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!-- 编辑表单 -->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form ref="newRow" :model="newRow" :rules="rules" label-width="100px">
        <el-form-item prop="distributionId" label="物资 ID">
          <el-input v-model="newRow.distributionId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="doneeId" label="受捐赠者 ID">
          <el-input v-model="newRow.doneeId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="suppliesName" label="物资名称">
          <el-input v-model="newRow.suppliesName"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="种类">
          <el-select v-model="newRow.type">
            <el-option value="防护类"></el-option>
            <el-option value="消毒类"></el-option>
            <el-option value="药品类"></el-option>
            <el-option value="诊断类"></el-option>
            <el-option value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="specifications" label="规格">
          <el-input v-model="newRow.specifications"></el-input>
        </el-form-item>
        <el-form-item prop="units" label="单位">
          <el-input v-model="newRow.units"></el-input>
        </el-form-item>
        <el-form-item prop="number" label="数量">
          <el-input v-model="newRow.number"></el-input>
        </el-form-item>
        <el-form-item prop="distributeTime" label="分配时间">
          <el-input v-model="newRow.distributeTime" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditedRow('newRow')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加表单（和编辑表单基本相同，但是受捐赠者ID需要填写） -->
    <el-dialog title="添加新的条目" :visible.sync="addFormVisible">
      <el-form ref="newRow" :model="newRow" :rules="rules" label-width="100px">
        <el-form-item prop="distributionId" label="物资 ID">
          <el-input v-model="newRow.distributionId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="doneeId" label="受捐赠者 ID">
          <el-input v-model="newRow.doneeId"></el-input>
        </el-form-item>
        <el-form-item prop="suppliesName" label="物资名称">
          <el-input v-model="newRow.suppliesName"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="种类">
          <el-select v-model="newRow.type">
            <el-option value="防护类"></el-option>
            <el-option value="消毒类"></el-option>
            <el-option value="药品类"></el-option>
            <el-option value="诊断类"></el-option>
            <el-option value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="specifications" label="规格">
          <el-input v-model="newRow.specifications"></el-input>
        </el-form-item>
        <el-form-item prop="units" label="单位">
          <el-input v-model="newRow.units"></el-input>
        </el-form-item>
        <el-form-item prop="number" label="数量">
          <el-input v-model="newRow.number"></el-input>
        </el-form-item>
        <el-form-item prop="distributeTime" label="分配时间">
          <el-input v-model="newRow.distributeTime" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNewRow('newRow')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 库存查看 -->
    <el-dialog title="库存查看" :visible.sync="stockVisible">
      <el-table :data="stock">
        <el-table-column prop="suppliesName" label="物资名称"></el-table-column>
        <el-table-column prop="type" label="种类"></el-table-column>
        <el-table-column prop="specifications" label="规格"></el-table-column>
        <el-table-column prop="units" label="单位"></el-table-column>
        <el-table-column prop="number" label="数量"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      distributionData: [
        {
          distributionId: "",
          doneeId: "",
          suppliesName: "",
          type: "",
          specifications: "",
          units: "",
          number: "",
          distributeTime: "",
        },
      ],
      stock: [
        {
          suppliesName: "",
          type: "",
          specifications: "",
          units: "",
          number: "",
        },
      ],
      searchForm: {
        doneeId: "",
        suppliesName: "",
      },
      totalRow: 100,
      currentPage: 1,
      pageSize: 15,
      // newRow 用于 添加行 和 编辑行 两处表单
      newRow: {
        distributionId: "",
        doneeId: "",
        suppliesName: "",
        type: "",
        specifications: "",
        units: "",
        number: "",
        distributeTime: "",
      },
      rules: {
        doneeId: [{ required: true, message: "受捐赠人ID为必填项" }],
        suppliesName: [{ required: true, message: "物资名称为必填项" }],
        number: [
          { required: true, message: "接收物资数量为必填项", trigger: "blur" },
        ],
      },
      editFormVisible: false,
      addFormVisible: false,
      stockVisible: false,
      isSearch: false,
    };
  },
  computed: {
    totalPage() {
      return Math.ceil(this.totalRow / this.pageSize);
    },
  },
  methods: {
    // [GET] 通过 当前页 和 每页显示的条数 更新表格信息
    getData(currentPage, pageSize) {
      this.axios
        .get("/distribution", {
          params: {
            currentPage: currentPage,
            pageSize: pageSize,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            // 更新当前表格信息（ps: 不知道这种直接赋值的方法是否可行，需要验证）
            this.distributionData = response.data;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },

    // [GET] 通过 捐赠者ID 和 物资名称 查找指定行
    search() {
      if (
        this.searchForm.doneeId === "" &&
        this.searchForm.suppliesName === ""
      ) {
        return false;
      }
      this.axios
        .get("/distribution/search", {
          params: {
            doneeId: this.searchForm.doneeId,
            suppliesName: this.searchForm.suppliesName,
          },
        })
        .then((response) => {
          if (response.status === 200) {
            this.isSearch = true;
            this.totalRow = response.data.totalRow;
            this.currentPage = 1;
            this.getData(this.currentPage, this.pageSize);
          }
        })
        .catch(() => {
          this.$message({
            message: "搜索失败",
            type: "error",
          });
        });
    },

    // 编辑按钮事件，初始化newRow，弹出编辑表单
    handleEdit(index, row) {
      this.oldNumber = parseInt(row.number);
      Object.getOwnPropertyNames(this.newRow).forEach((key) => {
        this.newRow[key] = row[key];
      });
      this.$prompt(
        "原数量为: " + this.oldNumber + ", 请输入新的数量",
        "更改数量",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^[0-9]{1,8}$/,
          inputErrorMessage: "请输入正确的格式",
        }
      )
        .then(({ value }) => {
          this.axios
            .get("/warehouse/number", {
              params: {
                suppliesName: row.suppliesName,
                specifications: row.specifications,
              },
            })
            .then((response) => {
              if (response.status === 200) {
                if (response.data.number >= value) {
                  this.newRow.number = value;
                  this.axios
                    .put("/distribution/edit", JSON.stringify(this.newRow))
                    .then((editResponse) => {
                      if (editResponse.status === 200) {
                        this.getData(this.currentPage, this.pageSize); // 更新表格信息
                        this.$message({
                          message: "更新成功",
                          type: "success",
                        });
                      }
                    })
                    .catch(() => {
                      this.$message({
                        message: "更新失败",
                        type: "error",
                      });
                    });
                } else {
                  this.$message({
                    message: "库存不足，修改前库存为" + response.data.number,
                    type: "error",
                  });
                }
              } else {
                this.$message({
                  message: "无法获取库存信息",
                  type: "error",
                });
              }
            });
        })
        .catch(() => {
          return false;
        });
    },

    // [delete] 删除表格中的一行信息
    handleDelete(index, id) {
      // console.log(index, id);
      this.$confirm("确定删除该行？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .delete("/distribution/delete", {
              params: {
                distributionId: id,
              },
            })
            .then((response) => {
              if (response.status === 200) {
                this.totalRow--; // 成功删除后，totalRow减一
                if (this.totalRow < this.currentPage * this.pageSize) {
                  this.currentPage--;
                }
                this.getData(this.currentPage, this.pageSize); // 更新表格信息
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
              }
              // console.log(response);
            })
            .catch((error) => {
              this.$message({
                message: "删除失败",
                type: "error",
              });
              console.error(error);
            });
        })
        .catch(() => {
          return false;
        });
    },

    // 处理添加按钮，弹出添加信息表单
    addRow() {
      // 清空newRow
      Object.getOwnPropertyNames(this.newRow).forEach((key) => {
        this.newRow[key] = "";
      });
      this.addFormVisible = true;
    },

    // [POST] 提交newRow，添加新的条目，更新表格信息
    submitNewRow(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 数量限制在1e9以下
          if (this.newRow.number >= 1e9) {
            this.$message({
              message: "数量过大",
              type: "error",
            });
            return false;
          }
          this.axios
            .get("/warehouse/number", {
              params: {
                suppliesName: this.newRow.suppliesName,
                specifications: this.newRow.specifications,
              },
            })
            .then((response) => {
              if (response.status === 200) {
                if (response.data.number >= this.newRow.number) {
                  // 物资存在且充足
                  this.axios
                    .post("/distribution/add", JSON.stringify(this.newRow))
                    .then((response) => {
                      // console.log(response);
                      if (response.status === 200) {
                        this.totalRow++;
                        this.getData(this.currentPage, this.pageSize); // 更新表格信息
                        this.addFormVisible = false;
                        this.$message({
                          message: "更新成功",
                          type: "success",
                        });
                      } else if (response.status === 403) {
                        this.$message({
                          message: "被捐赠人ID不存在",
                          type: "error",
                        });
                      }
                    })
                    .catch(() => {
                      this.$message({
                        message: "更新失败",
                        type: "error",
                      });
                    });
                } else if (response.data.number === 0) {
                  this.$message({
                    message: "物资不存在",
                    type: "error",
                  });
                } else {
                  this.$message({
                    message:
                      "物资不足，目前该物资数量为: " + response.data.number,
                    type: "error",
                  });
                }
              }
            });
        } else {
          return false;
        }
      });
    },

    // 处理用户翻页
    currentChange(val) {
      this.currentPage = val;
      this.getData(this.currentPage, this.pageSize);
    },

    // 处理每页显示总条数的变化
    sizeChange(val) {
      this.pageSize = val;
      this.getData(this.currentPage, this.pageSize);
    },

    exitSearch() {
      this.isSearch = false;
      this.searchForm.doneeId = "";
      this.searchForm.suppliesName = "";
      this.axios
        .get("/distribution/total")
        .then((response) => {
          if (response.status === 200) {
            this.totalRow = response.data.totalRow;
          }
        })
        .catch((error) => {
          console.error(error);
        });
      this.getData(this.currentPage, this.pageSize);
    },

    searchStock() {
      this.axios
        .get("/warehouse")
        .then((response) => {
          if (response.status === 200) {
            this.stock = response.data;
            this.stockVisible = true;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.axios
      .get("/distribution/total")
      .then((response) => {
        if (response.status === 200) {
          this.totalRow = response.data.totalRow;
        }
      })
      .catch((error) => {
        console.error(error);
      });
    this.getData(this.currentPage, this.pageSize);
  },
};
</script>

<style scoped>
.distribution-page {
  text-align: left;
}

.title {
  margin: 5px 0 0 15px;
}

.user-search {
  padding-left: 15px;
  display: flex;
  justify-content: space-between;
}

.el-pagination {
  margin-top: 20px;
  margin-bottom: 30px;
}

.el-dialog__body {
  padding-right: 100px !important;
  padding-left: 50px !important;
}

.el-dialog__footer {
  padding: 0 100px 30px 30px !important;
}
</style>